/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain (a) copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.sentry.ohos.core;

import ohos.app.Context;
import ohos.sensor.agent.CategoryEnvironmentAgent;
import ohos.sensor.bean.CategoryEnvironment;
import ohos.sensor.data.CategoryEnvironmentData;
import ohos.sensor.listener.ICategoryEnvironmentDataCallback;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.TestOnly;

import java.io.Closeable;
import java.io.IOException;

import io.sentry.Breadcrumb;
import io.sentry.IHub;
import io.sentry.Integration;
import io.sentry.SentryLevel;
import io.sentry.SentryOptions;
import io.sentry.util.Objects;

/**
 * TempSensorBreadcrumbsIntegration
 *
 * @since 2021-06-01
 */
public final class TempSensorBreadcrumbsIntegration
    implements Integration, Closeable, ICategoryEnvironmentDataCallback {
    @TestOnly
    CategoryEnvironmentAgent categoryEnvironmentAgent = new CategoryEnvironmentAgent();
    private final @NotNull Context context;
    private IHub ihub;
    private SentryOhosOptions sentryOhosOptions;

    /**
     * TempSensorBreadcrumbsIntegration
     *
     * @param context Context
     */
    public TempSensorBreadcrumbsIntegration(final @NotNull Context context) {
        this.context = Objects.requireNonNull(context, "Context is required");
    }

    @SuppressWarnings("deprecation")
    @Override
    public void register(final @NotNull IHub hub, final @NotNull SentryOptions options) {
        this.ihub = Objects.requireNonNull(hub, "Hub is required");
        this.sentryOhosOptions =
            Objects.requireNonNull(
                (options instanceof SentryOhosOptions) ? (SentryOhosOptions) options : null,
                "SentryOhosOptions is required");
        this.sentryOhosOptions
            .getLogger()
            .log(
                SentryLevel.DEBUG,
                "enableSystemEventsBreadcrumbs enabled: %s",
                this.sentryOhosOptions.isEnableSystemEventBreadcrumbs());

        if (this.sentryOhosOptions.isEnableSystemEventBreadcrumbs()) {
            if (categoryEnvironmentAgent != null) {
                final CategoryEnvironment defaultSensor = categoryEnvironmentAgent.getSingleSensor(CategoryEnvironment.SENSOR_TYPE_AMBIENT_TEMPERATURE);
                if (defaultSensor != null) {
                    categoryEnvironmentAgent.setSensorDataCallback(this, defaultSensor, 3);
                    options.getLogger().log(SentryLevel.DEBUG, "TempSensorBreadcrumbsIntegration installed.");
                } else {
                    this.sentryOhosOptions
                        .getLogger()
                        .log(SentryLevel.INFO, "TYPE_AMBIENT_TEMPERATURE is not available.");
                }
            } else {
                this.sentryOhosOptions.getLogger().log(SentryLevel.INFO, "SENSOR_SERVICE is not available.");
            }
        }
    }

    @Override
    public void close() throws IOException {
        if (categoryEnvironmentAgent != null) {
            categoryEnvironmentAgent.releaseSensorDataCallback(this);
            categoryEnvironmentAgent = null;
            if (sentryOhosOptions != null) {
                sentryOhosOptions.getLogger().log(SentryLevel.DEBUG, "TempSensorBreadcrumbsIntegration removed.");
            }
        }
    }

    @Override
    public void onSensorDataModified(CategoryEnvironmentData sensorData) {
        final float[] values = sensorData.values;

        // return if data is not available or zero'ed
        if (values == null || values.length == 0 || values[0] == 0f) {
            return;
        }
        if (ihub != null) {
            final Breadcrumb breadcrumb = new Breadcrumb();
            breadcrumb.setType("system");
            breadcrumb.setCategory("device.event");
            breadcrumb.setData("action", "TYPE_AMBIENT_TEMPERATURE");
            breadcrumb.setData("accuracy", sensorData.accuracy);
            breadcrumb.setData("timestamp", sensorData.timestamp);
            breadcrumb.setLevel(SentryLevel.INFO);
            breadcrumb.setData("degree", sensorData.values[0]); // Celsius
            ihub.addBreadcrumb(breadcrumb);
        }
    }

    @Override
    public void onAccuracyDataModified(CategoryEnvironment sensorBase, int i) {
    }

    @Override
    public void onCommandCompleted(CategoryEnvironment sensorBase) {
    }
}
